-- Copyright (c) 2015,2016 Lucky Byte, Inc.
--
-- Summary : 全渠道附加功能模块
--
-- Author  : 吴小虎 <xiaohu@lucky-byte.com>
-- Since   : 2016.4.29
--
-- History
--  * 2015.4.29 : 创建此文件
--

-- 代付交易确认后，检查此代付交易是否与消费代付订单相关，相关则更新消费代付订单状态
--
-- 参数 acp_uuid 是代付交易流水记录 UUID
--
local function _update_p1_order(acp_uuid, acp_rescode)
    local _table = jdbc.select([[
        select uuid from pay_p1_order where t40_uuid = ?
    ]], acp_uuid)

    if _table.count == 0 then
        logger.trace('交易[%s]与消费代付订单无关，无需处理...', acp_uuid)
        return
    end
    if _table.count > 1 then
        logger.fatal('交易[%s]与[%s]笔消费代付关联，请检查.', acp_uuid, _table.count)
        return
    end
    local _order_record = _table.get_record(0)
    local _order_uuid = _order_record.get('uuid')

    logger.debug('交易[%s]与消费代付订单[%s]关联，需进一步更新消费订单状态...',
        acp_uuid, _order_uuid)

    -- 更新消费代付订单状态
    local _status = acp_rescode == '00' and 4 or 3
    local _notes  = acp_rescode == '00' and '代付成功，已确认' or '代付失败，已确认'
    jdbc.update([[
        update pay_p1_order set status = ?, notes = ? where t40_uuid = ?
    ]], _status, _notes, acp_uuid)

    logger.info('更新消费代付订单[%s]状态为[%s-%s].', _order_uuid, _status, _notes)
end


-- 代付交易确认后，检查此代付交易是否与助农取款代付订单相关，相关则更新助农取款代付订单状态
--
-- 参数 acp_uuid 是代付交易流水记录 UUID
--
local function _update_p2_order(acp_uuid, acp_rescode, tr_status)
    local _table = jdbc.select([[
        select * from pay_p2_order where t40_uuid = ?
    ]], acp_uuid)

    if _table.count == 0 then
        logger.trace('交易[%s]与助农取款代付订单无关，无需处理...', acp_uuid)
        return
    end
    if _table.count > 1 then
        logger.fatal('交易[%s]与[%s]笔助农取款代付关联，请检查...',
            acp_uuid, _table.count)
        return
    end
    local _order_record = _table.get_record(0)
    local _order_uuid = _order_record.get('uuid')

    logger.debug('交易[%s]与助农代付订单[%s]关联，需进一步更新订单状态...',
        acp_uuid, _order_uuid)

    -- 更新订单状态
    local _status = acp_rescode == '00' and 4 or 3
    local _notes  = acp_rescode == '00' and '代付成功，已确认' or '代付失败，已确认'
    jdbc.update([[
        update pay_p2_order set status = ?, notes = ? where t40_uuid = ?
    ]], _status, _notes, acp_uuid)

    logger.info('更新助农代付订单[%s]状态为[%s-%s].', _order_uuid, _status, _notes)

    -- 如果代付交易失败，并且是从资金池扣取的手续费，则需要归还手续费到资金池
    -- 状态为 2 表示之前 ACP 代付交易成功，如果状态是 5，表示是追付代付交易成功，
    -- 如果状态是 3，那么之前就已经退还了手续费
    local _status = _order_record.get('status')
    if (_status == 2 or _status == 5) and acp_rescode ~= '00' and tr_status == 0 then
        if _order_record.get('fee_take_from') == 1 then
            logger.info(
                '助农代付订单[%s]的代付交易确认失败，归还之前扣取的手续费[%s]到资金池...',
                _order_uuid, _order_record.get('p2_fee')
            )
            local _table = jdbc.select([[
                select
                    json_extract_path_text(i_pkt, '42') as merno,
                    json_extract_path_text(i_pkt, '41') as termid
                from pay_trlist where uuid = ? and incoming = true
            ]], _order_record.get('t60_uuid'))

            local _t60_record = _table.get_record(0)
            local _p2_fund_uuid = _order_record.get('p2_fund_uuid')
            if not _p2_fund_uuid then
                notify.error('助农代付订单[%s]中未登记资金池，退还手续费失败.', _order_uuid)
                return
            end
            core.p2_fund.give_back({
                p2_fund_uuid = _p2_fund_uuid,
                amt    = _order_record.get('p2_fee'),
                merno  = _t60_record.get('merno'),
                termid = _t60_record.get('termid'),
            })
        end
    end
end


-- 更新追付记录
-- 如果追付失败，则重新进行追付
local function _update_t40_recvr(acp_uuid, acp_rescode)
    local _status = acp_rescode == '00' and 2 or 3
    local _notes  = acp_rescode == '00' and '代付成功，已确认' or '已确认代付失败，重新调度'
    local _done   = acp_rescode == '00' and true or false
    jdbc.update([[
        update pay_t40_recvr set done = ?, status = ?, notes = ?
            where done_uuid = ?
    ]], _done, _status, _notes, acp_uuid)
end


-- 构建全渠道交易报文中的身份认证字符串
--
local function _build_customer_info(args)
    local _custinfo = '{'
    if string.trimlen(args.acct_name) > 0 then
        _custinfo = _custinfo .. 'customerNm=' .. args.acct_name .. '&'
    end
    if string.trimlen(args.cred_no) > 0 then
        args.cred_type = tonumber(args.cred_type) or 1
        _custinfo = _custinfo .. 'certifTp=' ..
            string.pad(args.cred_type, 2, false, '0') .. '&'
        _custinfo = _custinfo .. 'certifId=' .. args.cred_no .. '&'
    end
    return string.sub(_custinfo, 1, string.len(_custinfo) - 1) .. '}'
end


core.acp_aux = {
    update_p1_order  = _update_p1_order,
    update_p2_order  = _update_p2_order,
    update_t40_recvr = _update_t40_recvr,
    build_custinfo   = _build_customer_info,
}
